<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="form" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="用户空间名称">
          <el-input
            v-model="queryParams.keywords"
            placeholder="用户空间名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" icon="el-icon-search">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <el-button type="success" @click="openDialog()"><i class="el-icon-circle-plus"></i> 添加工作空间</el-button>
      <el-button type="warning" @click="openMapDialog()"><i class="el-icon-circle-plus"></i> 映射工作空间</el-button>
      <el-button type="danger"><i class="el-icon-delete"></i> 删除</el-button>
    </el-card>

    <el-row :gutter="12" style="margin-top: 5px;">
      <el-col :span="6" style="margin-top: 10px;" v-for="data in dataList" :key="data.id">
        <el-card shadow="hover" @dblclick.native="openWorkspace(data)">
          <i class="el-icon-folder-opened" style="font-size: 50px;"/>
          <span>{{ data.name }}</span>
          <div style="float: right;">
            <i class="el-icon-edit" style="cursor: pointer;" @click="openDialog(data.id)"></i>
            <i class="el-icon-delete" style="margin-left: 10px; cursor: pointer;" @click="deleteWorkspace(data.id)"></i>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog
      :visible.sync="dialog.visible"
      :title="dialog.title"
      width="500px"
      :before-close="closeDialog">
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户空间名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入用户空间名称" />
        </el-form-item>

        <el-form-item label="是否共享" prop="share">
          <el-radio-group v-model="formData.share">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="所属用户" prop="sysUserId">
          <el-select v-model="formData.sysUserId" placeholder="请选择">
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addOrUpdate">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :visible.sync="workspaceDialog.visible" :title="workspaceDialog.title" width="80%" :close-on-click-modal="false">
      <div>
        <span v-for="(d, i) in breadcrumb" :key="d.name" style="cursor: pointer;" @click="switchBreadcrumb(d, i)"> / {{ d.name }}</span>
      </div>
      <el-card shadow="never" style="margin-top: 10px;">
        <el-upload
          class="upload-dialog"
          ref="upload"
          :action="uploadAction"
          :show-file-list="false"
          :on-change="submitUpload"
          :on-success="uploadFileSuccess"
          :headers="headers"
          :auto-upload="false">
          <el-button slot="trigger" style="margin-left: 5px;" type="success">上传文件</el-button>
          <div slot="tip" class="el-upload__tip"></div>
        </el-upload>
        <el-button style="margin-left: 10px;" type="success" @click="createDir">创建目录</el-button>
      </el-card>
      <el-table
        v-loading="loading"
        :data="fileList"
        highlight-current-row
        height="500px"
        border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="名称" prop="name" min-width="280" width="280">
          <template slot-scope="scope">
            <i class="el-icon-folder" v-if="!scope.row.file"></i>
            <i class="el-icon-document" v-if="scope.row.file"></i>
            <span style="margin-left: 10px">
              <label v-if="!scope.row.input">{{ scope.row.name }}</label>
              <el-input v-if="scope.row.input" style="width: 80%;" v-model="scope.row.name" placeholder="请输入文件名" @keyup.enter.native="renameFile(scope.row)"></el-input>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="修改日期" prop="updateTimeText"/>
        <el-table-column label="类型" prop="suffix"/>
        <el-table-column label="大小" prop="sizeFormat"/>
        <el-table-column fixed="right" label="操作" min-width="220" width="220">
          <template #default="scope">
            <el-tag type="info" style="cursor: pointer;" @click="rename(scope)">重命名</el-tag>
            <el-tag type="danger" style="margin-left: 5px; cursor: pointer;" @click="deleteFile(scope.row.id)">删除</el-tag>
            <el-tag v-if="!scope.row.file" type="success" style="margin-left: 5px; cursor: pointer;" @click="openNewDir(scope.row)">打开目录</el-tag>
            <el-tag v-if="scope.row.file" type="warning" style="margin-left: 5px; cursor: pointer;" @click="downloadFile(scope.row)">下载文件</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog
      :visible.sync="mapDialog.visible"
      :title="mapDialog.title"
      width="500px">
      <el-form
        ref="userFormMapRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户空间名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入用户空间名称" />
        </el-form-item>

        <el-form-item label="映射路径" prop="basePath">
          <el-input v-model="formData.basePath" placeholder="请输入映射路径（服务器路径）" />
        </el-form-item>

        <el-form-item label="是否共享" prop="share">
          <el-radio-group v-model="formData.share">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="所属用户" prop="sysUserId">
          <el-select v-model="formData.sysUserId" placeholder="请选择">
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="mappingWorkspace">确 定</el-button>
          <el-button @click="closeMappingDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import userApi from '@/api/system/user'
import workspaceApi from '@/api/system/workspace'
import fileApi from '@/api/system/file'
import { Session } from '@/utils/storage'
import { formatDate } from '@/utils/formatTime'

export default {
	name: 'workspaceIndex',
	data() {
		return {
			queryParams: {
        keywords: '',
        pageNum: 0,
        pageSize: 10,

      },
      total: 0,
      loading: false,
      dataList: [],
      ids: [],
      roleDialogVisible: false,
      roleList: [],
      selectedWorkspace: {},
      dialog: {},
      formData: {},
      rules: {},

      userList: [],
      workspaceDialog: {},
      fileList: [],
      uploadFileList: [],
      uploadAction: '',
      headers: {},
      parentDir: {
        id: -1,
        path: '/'
      },
      renameInput: '',
      breadcrumb: [],

      mapDialog: {},
		};
	},
  mounted () {
    this.headers = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    };
  },
  methods: {
    downloadFile (data) {
      fileApi.download(data.id).then((res) => {
        const blob = new Blob([res.data]); 
        const elink = document.createElement('a');
        elink.download = data.name;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href);
        document.body.removeChild(elink);
      });
    },
    mappingWorkspace () {
      this.loading = true;
      workspaceApi.mapping(this.formData).then((res) => {
        this.loading = false;
        this.$message({message: '用户空间映射成功！', type: 'success'});
        this.closeMappingDialog();
      });
    },
    closeMappingDialog () {
      this.$set(this.mapDialog, 'visible', false);
      this.$set(this.mapDialog, 'title', '');
      this.handleQuery();
    },
    openMapDialog () {
      userApi.list().then(r => {
        this.userList = r.data;
        this.$set(this.mapDialog, 'visible', true);
        this.$set(this.mapDialog, 'title', '映射用户空间');
        this.formData = {};
      });
    },
    switchBreadcrumb (data, i) {
      let breadcrumb = this.breadcrumb;
      if (breadcrumb.length == (i + 1)) {
        return;
      }
      breadcrumb = breadcrumb.slice(0, i + 1);
      this.breadcrumb = breadcrumb;
      this.parentDir = {
        id: -1,
        path: '/'
      };
      if (i != 0) {
        this.parentDir = {
          id: data.id,
          path: data.path,
        };
      }
      this.updateFileList();
    },
    openNewDir (row) {
      this.parentDir = row;
      this.breadcrumb.push({
        name: row.name,
        type: 'file',
        path: row.path,
        id: row.id
      });
      this.uploadAction = process.env.VUE_APP_FILE_API_PREV + '/file/upload/' + this.selectedWorkspace.id + '/' + this.parentDir.id
      this.updateFileList();
    },
    deleteFile (id) {
      fileApi.delete(id).then((res) => {
        this.$message({message: '文件删除成功！', type: 'success'});
      this.updateFileList();
      })
    },
    uploadFileSuccess () {
      this.$message({message: '文件上传成功！', type: 'success'});
      this.updateFileList();
    },
    renameFile (data) {
      fileApi.rename({
        name: data.name,
        id: data.id
      }).then((res) => {
        this.$message({message: '重命名成功！', type: 'success'});
        this.updateFileList();
      })
    },
    rename (scope) {
      let index = scope.$index
      let data = this.fileList[index];
      data.input = true;
      this.$set(this.fileList, index, data);
    },
    createDir () {
      let params = {
        name: '新建文件夹',
        workspaceId: this.selectedWorkspace.id,
        parentId: this.parentDir.id
      };
      fileApi.addDir(params).then((res) => {
        this.$message({message: '目录创建成功！', type: 'success'});
        this.updateFileList();
      })
    },
    submitUpload (file, fileList) {
      this.$refs.upload.submit();
    },
    openWorkspace (data) {
      this.$set(this.workspaceDialog, 'visible', true);
      this.$set(this.workspaceDialog, 'title', data.name);
      
      this.selectedWorkspace = data;
      this.parentDir = {
        id: -1,
        path: '/'
      }
      this.uploadAction = process.env.VUE_APP_FILE_API_PREV + '/file/upload/' + this.selectedWorkspace.id + '/' + this.parentDir.id
      this.breadcrumb = [];
      this.breadcrumb.push({
        name: data.name,
        type: 'workspace',
        id: data.id,
      });
      this.updateFileList();
    },
    updateFileList () {
      this.loading = true;
      fileApi.list(this.selectedWorkspace.id, this.parentDir.id).then((res) => {
        this.fileList = res.data;
        this.fileList.forEach(v => {
          v.updateTimeText = formatDate(new Date(v.updateTime), "YYYY-mm-dd HH:MM:SS")
          v.sizeFormat = v.size ? v.size.toFixed(1) + ' kb' : ''
          v.input = false
        })
        this.loading = false;
      });
    },
    handleQuery() {
      this.loading = true;
      let params = {
        number: this.queryParams.pageNum,
        size: this.queryParams.pageSize
      };
      workspaceApi.page(params).then((res) => {
        let data = res.data;
        this.dataList = data.content;
        this.total = data.count;
        this.loading = false;
      }).catch(() => {});
    },
    resetQuery() {
      this.queryParams = {
        keywords: '',
        pageNum: 0,
        pageSize: 10,
      };
      this.handleQuery();
    },
    
    addOrUpdate() {
      let that = this;
      if (this.formData.id) {
        workspaceApi.update(this.formData).then((res) => {
          this.$message({message: '用户空间更新成功！', type: 'success'});
          that.closeDialog();
        });
      } else {
        workspaceApi.add(this.formData).then((res) => {
          this.$message({message: '用户空间添加成功！', type: 'success'});
          that.closeDialog();
        });
      }
    },
    openDialog(id) {
      this.$set(this.dialog, 'visible', true);
      this.formData = {};
      let that = this;
      userApi.list().then(r => {
        this.userList = r.data;
        if (id) {
          this.$set(this.dialog, 'title', '编辑用户空间');
          workspaceApi.get(id).then((res) => {
              let data = res.data;
              that.formData = data;
          });
        } else {
          this.$set(this.dialog, 'title', '新增用户空间');
          that.formData = {};
        }
      });
      

    },
    closeDialog() {
      this.$set(this.dialog, 'visible', false);
      this.$set(this.dialog, 'title', '');
      this.handleQuery();
    },
    deleteWorkspace(id) {
      if (id) {
        workspaceApi.delete(id).then((res) => {
          this.$message({message: '用户空间删除成功！', type: 'success'});
          this.handleQuery();
        });
      } else {
        this.$message.error('暂不支持批量删除用户空间！');
      }
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.handleQuery();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.handleQuery();
    },
  },
  created() {
    this.handleQuery();
  }
};
</script>


<style scoped>
.upload-dialog {
  width: 110px;
  float: left;
}
</style>
